import { defineStore } from 'pinia'

let reconnectTimer = null

export const useUserSocketStore = defineStore('userSocket', {
  state: () => ({
    isConnected: false,
    isManuallyClosed: false,
    reconnectCount: 0,
    urlCache: '',
    onMessageCallbacks: [],
  }),

  actions: {
    connect(url) {
      if (!url || this.isConnected) return

      this.urlCache = url
      this.isManuallyClosed = false

      console.log(`🚀 [用户端] 正在连接 WebSocket -> ${url}`)
      uni.connectSocket({
        url,
        header: {
          'Authorization': 'Bearer ' + uni.getStorageSync('token'),
        }
      })

      uni.onSocketOpen(this.handleOpen)
      uni.onSocketMessage(this.handleMessage)
      uni.onSocketClose(this.handleClose)
      uni.onSocketError(this.handleError)
    },

    handleOpen() {
      console.log('✅ [用户端] WebSocket 已连接')
      this.isConnected = true
      this.reconnectCount = 0
    },

    handleMessage(res) {
      try {
        const data = JSON.parse(res.data)
        console.log('📩 [用户端] 收到消息：', data)
        this.onMessageCallbacks.forEach(cb => cb(data))
      } catch (e) {
        console.error('❌ [用户端] 消息解析失败', e)
      }
    },

    handleClose() {
      console.warn('🔌 [用户端] WebSocket 已关闭')
      this.isConnected = false
      if (!this.isManuallyClosed) this.tryReconnect()
    },

    handleError(err) {
      console.error('💥 [用户端] WebSocket 错误:', err)
      if (!this.isManuallyClosed) this.tryReconnect()
    },

    tryReconnect() {
      if (this.isManuallyClosed) {
        console.log('🚫 [用户端] 手动关闭，不再重连')
        return
      }

      reconnectTimer && clearTimeout(reconnectTimer)
      reconnectTimer = setTimeout(() => {
        this.reconnectCount++
        console.log(`♻️ [用户端] 第 ${this.reconnectCount} 次尝试重连`)
        this.connect(this.urlCache)
      }, 5000)
    },

    send(data) {
      if (!this.isConnected) {
        uni.showToast({
          title: '连接中，请稍后再试',
          icon: 'none'
        })
        return { success: false }
      }

      uni.sendSocketMessage({
        data: JSON.stringify(data),
        success: () => console.log('📤 [用户端] 消息发送成功:', data),
        fail: (err) => console.error('❌ [用户端] 消息发送失败:', err)
      })
      return { success: true }
    },

    close() {
      console.log('🛑 [用户端] 主动关闭 WebSocket')
      this.isManuallyClosed = true
      this.isConnected = false
      clearTimeout(reconnectTimer)
      uni.closeSocket()
    },

    subscribe(callback) {
      if (typeof callback === 'function') this.onMessageCallbacks.push(callback)
    },

    unsubscribe(callback) {
      this.onMessageCallbacks = this.onMessageCallbacks.filter(cb => cb !== callback)
    }
  }
})
